let isGettingAlbums = false;
let image = document.getElementsByClassName('image');
let albumContent = document.getElementsByClassName('album-content')[0];
let params = new URLSearchParams(location.search);
id = params.get('id');
uid = params.get('uid');
function iniAlbum() {
  let userIcon = document.getElementsByClassName('user-icon')[0];
  loadHeadImg();
  isLogin();
  getAllAlbums(sessionStorage.getItem('id'));
  if(sessionStorage.getItem('headImg') == 'null') {
    userIcon.src = '../img/user-icon.png';
  }else {
    userIcon.src = 'http://' + sessionStorage.getItem('headImg');
  }
  document.getElementsByClassName('username')[0].innerHTML = sessionStorage.getItem('username')
}
function iniAlbumDetail() {
  let horizontalNav = document.getElementsByClassName('horizontal-nav')[0];
  loadHeadImg();
  isLogin();
  const userData = {
    uid
  }
  request('http://175.178.51.126:8091/smallA/selectAlbumByUid', 'POST', JSON.stringify(userData))
    .then(value => {
      console.log(value);
      if(value.code == 200) {
        let targetAlbum = value.data.filter(data => {
          return data.id == id;
        })
        console.log(targetAlbum)
        if(targetAlbum.length != 0) {
          horizontalNav.innerHTML = `
          <button class="primary medium back" onclick="history.back(-1)">◀</button>
          <img src="../img/album.png" alt="相册图标" style="border-radius:0">
          <span class="album-name"></span>
          <p class="album-intro"></p>
          <button type="button" class="primary full" onclick="changeUploadPage('open')">上传图片</button>
          <button type="button" class="danger full delete-album">删除相册</button>
          `;
          document.getElementsByClassName('album-name')[0].innerHTML = targetAlbum[0].name;
          document.getElementsByClassName('album-intro')[0].innerHTML = '简介：' + targetAlbum[0].introduction;
          loadAllAlbumImg(targetAlbum[0]);
          let deleteAlbumBtn = document.getElementsByClassName('danger full delete-album')[0];
          deleteAlbumBtn.addEventListener('click', () => {
            confirmBox('open', id, '确认删除该相册？', '删除后不可恢复。', deleteAlbum)
          })
        }
      }else {
        albumContent.innerHTML = '<p style="width:100%;text-align:center">' + value.msg + '</p>'
      }
    }).catch(error => {
      albumContent.innerHTML = '<p style="width:100%;text-align:center">'+ error +'</p>'
    })
}
function getAllAlbums(id) {
  albumContent.innerHTML = '<p style="width:100%;text-align:center">正在加载相册...</p>'
  albumContent = document.getElementsByClassName('album-content')[0];
  const userData = {
    uid: id
  }
  isGettingAlbums = true;
  request('http://175.178.51.126:8091/smallA/selectAlbumByUid', 'POST', JSON.stringify(userData))
    .then(value => {
      console.log(value);
      if(value.code == 200) {
        albumContent.innerHTML = '';
        for(let i=0;i<value.data.length;i++) {
          let albumDiv = document.createElement('div');
          albumDiv.className = 'album';
          albumDiv.innerHTML = `
          <a href="album-detail.html?id=${value.data[i].id}&uid=${id}">
            <img src="../img/album.png"/>
            <p>${value.data[i].name}</p>
          </a>
          `
          albumContent.appendChild(albumDiv);
        }
      }else if(value.code == 419) {
        albumContent.innerHTML = '<p style="width:100%;text-align:center">相册为空！</p>';
      }
      isGettingAlbums = false;
    }).catch(error => {
      albumContent.innerHTML = error;
    })
}
function changeCreatePage(operation) {
  if(!isGettingAlbums) {
    let body = document.getElementsByTagName('body')[0];
    if(operation == 'open') {
      let headImg = sessionStorage.getItem('headImg');
      if(headImg == 'null'){
        headImg = path + 'img/user-icon.png';
      }else {
        headImg = 'http://' + headImg;
      }
     let layerDiv = document.createElement('div');
     layerDiv.setAttribute('class','layer');
     layerDiv.innerHTML += `
        <div class="create-news">
          <div class="close" onclick="changeCreatePage('close')">X</div>
          <div class="form">
            <form method="post" name="post-news">
              <input type="text" name="title" value="" placeholder="相册名"/>
              <textarea name="intro" placeholder="相册介绍"></textarea>
              <div class="operation">
                <button type="button" class="primary large" onclick="createAlbum()">创建</button>
              </div>
            </form>
          </div>
          </div>
        </div>
     `
     document.body.appendChild(layerDiv);
    }else if(operation == 'close') {
      let layer = document.getElementsByClassName('layer')[0];
      body.removeChild(layer);
    }
  }
}
function changeUploadPage(operation) {
  if(!isGettingAlbums) {
    let body = document.getElementsByTagName('body')[0];
    if(operation == 'open') {
     let layerDiv = document.createElement('div');
     layerDiv.setAttribute('class','layer');
     layerDiv.innerHTML += `
        <div class="create-news">
          <div class="close" onclick="changeUploadPage('close')">X</div>
            <div class="form">
              <div class="operation">
                <div class="select-img">
                  <button class="primary large">选择图片</button>
                  <input type="file" name="img" multiple onchange="showFileInfo('album')"/>
                </div>
                <button type="button" class="primary large" onclick="uploadImg()" id="uploadBtn">上传</button>
              </div>
            </div>
          </div>
        </div>
     `
     document.body.appendChild(layerDiv);
    }else if(operation == 'close') {
      let layer = document.getElementsByClassName('layer')[0];
      body.removeChild(layer);
    }
  }
}
function createAlbum() {
  const createData = {
    uid: sessionStorage.getItem('id'),
    name: document.getElementsByName('title')[0].value,
    introduction: document.getElementsByName('intro')[0].value
  };
  if(createData.name != '') {
    albumContent = document.getElementsByClassName('album-content')[0];
    request('http://175.178.51.126:8091/smallA/insertAlbum','POST', JSON.stringify(createData))
      .then(value => {
        console.log(value);
        if(value.code == 200) {
          changeCreatePage('close');
          albumContent.innerHTML = '';
          getAllAlbums(sessionStorage.getItem('id'));
        }else {
          alert(value.msg);
        }
      }).catch(error => {
        console.log(error);
      })
  }else{
    alert('请输入相册名后再创建！');
  }
}
function loadAllAlbumImg(album) {
  albumContent = document.getElementsByClassName('album-content')[0];
  albumContent.innerHTML = '';
  if(album.photos.length != 0) {
    let timer = null;
    for(let i=0;i<album.photos.length;i++) {
      albumContent.innerHTML += `
      <div class="img-area">
        <img src="../img/image.png" data-src="${album.photos[i].img}" id="${album.photos[i].id}" onclick="openImg(this)" class="album-img"/>
        <div class="delete-img danger">删除</div>
      </div>
      `
    }
    let albumImg = albumContent.getElementsByClassName('album-img');
    lazyLoadImg(albumImg);
    document.addEventListener('scroll',function () {
      if (timer) clearTimeout(timer);
      timer = setTimeout(() => {
        lazyLoadImg(albumImg);
      },100);
    })
  }else {
    albumContent.innerHTML = `<p style="width:100%;text-align:center">还没有图片！</p>`
  }
}
function uploadImg() {
  document.getElementById('uploadBtn').setAttribute('disabled','disabled');
  document.getElementById('uploadBtn').setAttribute('class','primary large disabled');
  formData.append('uid', uid);
  formData.append('aid', id);
  request('http://175.178.51.126:8091/smallA/uploadPhoto','POST',formData, 'none')
    .then(value => {
      console.log(value);
      if(value.code == 200) {
        changeUploadPage('close')
        iniAlbumDetail()
      }else {
        alert('请选择图片上传！');
        document.getElementById('uploadBtn').removeAttribute('disabled');
        document.getElementById('uploadBtn').setAttribute('class','primary large');
      }
    }).catch(error => {
      console.log(error);
    })
}
function deleteImg(id) {
  const deleteData = {
    id: id
  }
  request('http://175.178.51.126:8091/smallA/deletePhoto','POST', JSON.stringify(deleteData))
    .then(value => {
      console.log(value);
      if(value.code == 200) {
        confirmBox('close');
        iniAlbumDetail()
      }
    })
}
albumContent.addEventListener('click', event => {
  if(event.target.className == 'delete-img danger') {
    confirmBox('open', event.target.previousElementSibling.id, '确认删除该照片？', '删除后不可恢复。', deleteImg);
  }
})
function deleteAlbum(id) {
  const albumData = {
    id: id
  }
  request('http://175.178.51.126:8091/smallA/deleteAlbum','POST', JSON.stringify(albumData))
    .then(value => {
      console.log(value);
      if(value.code == 200) {
        location.href = 'album.html';
      }
    }).catch(error => {
      console.log(error);
    })
}